#!/bin/sh
# 输出日志信息
echo "-------------------"
echo "本次构建的目录&缓存命中&构建hash"
echo "格式："
echo "模块名 缓存命中状态 构建的哈希值"
echo ""
# 创建缓存备份目录
mkdir ./node_modules/.cache/turbo_bak

cat ./.module_logs/build_log.txt \
  | grep -E -o "@hera\/.*(miss|hit).+$" \
  | sed -e 's/:build: cache//g' \
  | sed -e 's/, executing//g' \
  | sed -e 's/, replaying output//g' \
  | sed -e 's/, suppressing output//g' \
  | while read -r line; do
      if [[ "${line}" =~ "miss" ]]; then
        cache=" miss "
      else
        cache=" hit "
      fi
      module=${line%${cache}*}
      hash=${line#*${cache}}
      echo "module:" $module
      echo "cache:" $cache
      echo "hash:" $hash
      # 根据本次构建产生的缓存hash备份到 turbo_bak/
      mv "node_modules/.cache/turbo/${hash}-meta.json" "node_modules/.cache/turbo_bak/"
      mv "node_modules/.cache/turbo/${hash}.tar.zst" "node_modules/.cache/turbo_bak/"
      echo ""
    done

# 统一删除原来缓存目录中不涉及本次构建的缓存文件
rm -f ./node_modules/.cache/turbo/**
# 把本次构建相关的缓存文件还原回原来的目录
mv ./node_modules/.cache/turbo_bak/** ./node_modules/.cache/turbo
# 删除备份目录
rm -rf ./node_modules/.cache/turbo_bak
ls -l ./node_modules/.cache/turbo
